import React, { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Card, CardHeader, CardTitle, CardContent, CardFooter } from '@/components/ui/card';
import { Copy, RefreshCw, Database } from 'lucide-react';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import OpenAIClient from '@/lib/llm';
import ReactMarkdown from 'react-markdown';
import rehypeHighlight from 'rehype-highlight';
import 'highlight.js/styles/atom-one-dark.css';

const SQLGenerator = () => {
  const [input, setInput] = useState('');
  const [output, setOutput] = useState('');
  const [dbType, setDbType] = useState('mysql'); // 默认选择MySQL
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');
  const client = new OpenAIClient();

  const generateSQL = async () => {
    if (!input.trim()) {
      setError('请输入需求描述');
      return;
    }
    
    setLoading(true);
    setError('');
    try {
      const messages = [
        {
          role: 'system',
          content: `你是一个专业的 SQL 生成器，将根据用户需求生成 ${dbType} 数据库的 SQL 语句。确保输出的 SQL 语法正确，并且满足用户需求。
          只返回 SQL 语句，不要解释。也不要写出`+'```sql ```，建议和意见以注释格式写出。'
        },
        {
          role: 'user',
          content: input
        }
      ];
      
      const response = await client.chat(messages);
      setOutput(response);
    } catch (err) {
      console.error('生成 SQL 出错:', err);
      setError('生成 SQL 时出错，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  const copyToClipboard = () => {
    navigator.clipboard.writeText(output);
  };

  return (
    <Card className="h-full flex flex-col">
      <CardHeader className="pb-3">
        <div className="flex items-center gap-3">
          <Database className="text-blue-500" size={24} />
          <CardTitle>SQL生成器</CardTitle>
        </div>
      </CardHeader>
      <CardContent className="flex-1 grid gap-4">
        <div>
          <label className="block mb-2 text-sm font-medium">数据库类型</label>
          <Select value={dbType} onValueChange={setDbType}>
            <SelectTrigger className="w-full">
              <SelectValue placeholder="选择数据库类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="mysql">MySQL</SelectItem>
              <SelectItem value="sqlite">SQLite</SelectItem>
              <SelectItem value="postgresql">PostgreSQL</SelectItem>
              <SelectItem value="oracle">Oracle</SelectItem>
              <SelectItem value="sqlserver">SQL Server</SelectItem>
            </SelectContent>
          </Select>
        </div>
        
        <div>
          <label className="block mb-2 text-sm font-medium">输入需求描述</label>
          <Textarea
            value={input}
            onChange={(e) => setInput(e.target.value)}
            placeholder="例如：查询用户表中最近7天的活跃用户"
            className="min-h-[120px]"
          />
        </div>
        
        <div>
          <label className="block mb-2 text-sm font-medium">生成的SQL</label>
          <div className="relative">
            <div className="bg-gray-50 rounded-md p-4 font-mono text-sm overflow-auto max-h-[300px]">
              {loading && <div>生成中...</div>}
              {error && <div className="text-red-500">{error}</div>}
              {output ? (
                 <div className="prose prose-zinc max-w-none dark:prose-invert min-h-[100px] w-full">
                   <ReactMarkdown 
                     rehypePlugins={[rehypeHighlight]}
                   >
                     {`\`\`\`sql\n${output}\n\`\`\``}
                   </ReactMarkdown>
                 </div>
               ) : (
                 <div className="bg-gray-50 rounded-md p-4 font-mono text-sm text-gray-500 min-h-[100px] w-full">
                   生成的SQL将显示在这里
                 </div>
               )}
            </div>
            {output && !loading && (
              <Button 
                size="icon" 
                variant="ghost" 
                className="absolute top-2 right-2"
                onClick={copyToClipboard}
              >
                <Copy size={16} />
              </Button>
            )}
          </div>
        </div>
      </CardContent>
      <CardFooter>
        <Button onClick={generateSQL} className="w-full" disabled={loading}>
          {loading ? (
            <>加载中...</>
          ) : (
            <> <RefreshCw className="mr-2" size={16} /> 生成SQL </>
          )}
        </Button>
      </CardFooter>
    </Card>
  );
};

export default SQLGenerator;
